package com.egao.common.component.minio.config;

import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;

/**
 * Minio 配置
 * 存储桶要配置 readOnly
 *
 * @author lym
 */
@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    @Value("${service}")
    private String service;

    @Value("${spring.profiles.active}")
    private String active;

    @Bean
    public MinioClient minioClient() throws InvalidPortException, InvalidEndpointException {
        TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // Do nothing (trust any client certificate)
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // Do nothing (trust any server certificate)
                    }
                }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpClient customHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier((hostname, session) -> true)
                .build();

        if ("prod".equals(active)) {
            return new MinioClient(service, 9000, accessKey, secretKey, "us-east-1", true, customHttpClient);
        } else {
            return new MinioClient(endpoint, accessKey, secretKey);
        }

    }




}
